#include "cameradlg.h"
#include "ui_cameradlg.h"

#include <QHBoxLayout>

CameraDlg::CameraDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CameraDlg)
{
    ui->setupUi(this);
    this->resize(600, 400);

    pCamera = new QCamera();
    pCameraViewFinder = new QCameraViewfinder();
    pCameraImageCapture = new QCameraImageCapture(pCamera);
    pbtnCapture = new QPushButton();
    pbtnSave = new QPushButton();
    pbtnExit = new QPushButton();
    pLabelDisplay = new QLabel();

    QHBoxLayout *mainLayout = new QHBoxLayout();
    QVBoxLayout *vLayout = new QVBoxLayout();

    pLabelDisplay->setFixedSize(150, 150);
    pLabelDisplay->setScaledContents(true);

    vLayout->addWidget(pLabelDisplay);
    vLayout->addStretch();
    vLayout->addWidget(pbtnCapture);
    vLayout->addWidget(pbtnSave);
    vLayout->addWidget(pbtnExit);

    mainLayout->addWidget(pCameraViewFinder);
    mainLayout->addLayout(vLayout);

    connect(pbtnCapture, &QPushButton::clicked, this, &CameraDlg::captureImage);
    connect(pbtnSave, &QPushButton::clicked, this, &CameraDlg::saveImage);
    connect(pbtnExit, &QPushButton::clicked, this, &CameraDlg::close);
    connect(pCameraImageCapture, &QCameraImageCapture::imageCaptured, this, &CameraDlg::displayImage);

    pCameraImageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
    pCamera->setCaptureMode(QCamera::CaptureStillImage);
    pCamera->setViewfinder(pCameraViewFinder);
    pCamera->start(); //启动摄像头

    this->setLayout(mainLayout);
    this->translateLanguage();
}

CameraDlg::~CameraDlg()
{
    delete ui;
}

void CameraDlg::translateLanguage()
{
    this->setWindowTitle("testCapture");
    pbtnCapture->setText(tr("capture"));
    pbtnSave->setText(tr("save"));
    pbtnExit->setText(tr("exit"));
}

void CameraDlg::displayImage(int id, QImage image)
{
    pLabelDisplay->setPixmap(QPixmap::fromImage(image));
}

void CameraDlg::captureImage()
{
    //截图
    pCameraImageCapture->capture();
}

void CameraDlg::saveImage()
{
    const QPixmap *pixmap = pLabelDisplay->pixmap();
    if(pixmap)
    {
        pixmap->save("D://Study/QtCameraTest/QtCameraTest/Debug/debug/a.jpg");
    }
}
